package controllers;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.BeanUsers;
import utils.DAOUser;

/**
 * Servlet implementation class SearchController
 */
public class SearchController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SearchController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userSearch = null;

		HttpSession session = request.getSession();

		synchronized (session) {
			String user = (String) session.getAttribute("user");

			if (session.getAttribute("search") != null)
				userSearch = (String) session.getAttribute("search");
			if (request.getParameter("search") != null
					&& !request.getParameter("search").equals(""))
				userSearch = request.getParameter("search");

			int numUsers = 5;
			if (request.getParameter("numUsers") != null)
				numUsers = Integer.parseInt(request.getParameter("numUsers"));
			else if (session.getAttribute("numUsers") != null)
				numUsers = (Integer) session.getAttribute("numUsers");

			session.setAttribute("numUsers", numUsers);

			try {
				if (userSearch != null && !userSearch.equals("")) {
					BeanUsers beanUsers = new BeanUsers();
					DAOUser daouser = new DAOUser();

					beanUsers.setUsers(daouser.getusers(userSearch, numUsers));
					daouser.setFollowers(beanUsers.getUsers(), user);
					daouser.setContacts(beanUsers.getUsers(), user);

					request.setAttribute("beanUsers", beanUsers);
				}
				session.setAttribute("contentView", "SearchController");
				session.setAttribute("search", userSearch);

				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/users.jsp");
				if (dispatcher != null)
					dispatcher.forward(request, response);
			} catch (Exception e) {
				// TODO: handle exceptione
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
